package com.llt.chatroom.controller;

import com.llt.chatroom.model.Friend;
import com.llt.chatroom.model.User;
import com.llt.chatroom.service.FriendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Slf4j
@RestController
@Transactional(rollbackFor = {Exception.class})
public class FriendController {

    @Resource
    FriendService friendService;

    @GetMapping("/friendList")
    public Object getFriendList(HttpServletRequest req) {

        // 1. 从会话中获取到 userId
        HttpSession session = req.getSession(false);
        if (session == null) {
            log.error("未登录");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            log.error("未登录");
            return new ArrayList<Friend>();
        }

        // 2. 查结果并且返回
        return friendService.getFriendList(user.getUserId());
    }

//    根据用户名称获取好友
    @RequestMapping("/searchFriend")
    public Object searchFriend(String userName) {
        log.info("查询用户："+ userName);
        return friendService.searchFriend(userName);
    }
}
